import os
import time
import subprocess
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def check_adb_connection():
    """检查ADB连接状态"""
    try:
        result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
        logging.info(f"ADB设备状态: {result.stdout}")
        if 'unauthorized' in result.stdout:
            logging.error("ADB设备未授权，请在设备上确认授权请求")
            return False
        if 'device' not in result.stdout:
            logging.error("未找到已连接的ADB设备")
            return False
        return True
    except Exception as e:
        logging.error(f"检查ADB连接时出错: {str(e)}")
        return False

def make_phone_call(phone_number):
    """拨打电话并开启免提"""
    logging.info(f"准备拨打电话: {phone_number}")
    
    if not check_adb_connection():
        logging.error("ADB连接检查失败，无法拨打电话")
        return False
        
    try:
        # 使用 adb shell am start 启动拨号界面
        dial_command = f'adb shell am start -a android.intent.action.CALL -d tel:{phone_number}'
        logging.info(f"执行拨号命令: {dial_command}")
        
        result = subprocess.run(dial_command, shell=True, capture_output=True, text=True)
        if result.returncode != 0:
            logging.error(f"拨号命令执行失败: {result.stderr}")
            return False
            
        logging.info("拨号命令执行成功，等待电话接通...")
        # 等待电话接通
        time.sleep(5)  # 可以根据实际情况调整等待时间
        
        # 尝试多种方式开启免提
        enable_speaker()
        return True
        
    except Exception as e:
        logging.error(f"拨打电话失败: {str(e)}")
        return False

def enable_speaker():
    """使用多种方式尝试开启免提"""
    methods = [
        # 方法1: 使用坐标点击
        lambda: subprocess.run('adb shell input tap 867 1820', shell=True, capture_output=True, text=True),
        
        # 方法2: 使用音频管理器命令
        lambda: subprocess.run('adb shell am broadcast -a android.intent.action.MEDIA_BUTTON '
                             '--ei android.intent.extra.KEY_CODE 24', shell=True, capture_output=True, text=True),
        
        # 方法3: 使用音频服务命令
        lambda: subprocess.run('adb shell service call audio 7', shell=True, capture_output=True, text=True),
        
        # 方法4: 模拟按键事件
        lambda: subprocess.run('adb shell input keyevent KEYCODE_SPEAKER', shell=True, capture_output=True, text=True)
    ]
    
    for method in methods:
        try:
            result = method()
            if result.returncode != 0:
                logging.error(f"开启免提方法执行失败: {result.stderr}")
                continue
            logging.info("开启免提方法执行成功")
            time.sleep(1)  # 给每个方法一些执行时间
        except Exception as e:
            logging.error(f"方法执行失败: {str(e)}")
            continue

def end_call():
    """结束通话"""
    try:
        result = subprocess.run('adb shell input keyevent KEYCODE_ENDCALL', shell=True, capture_output=True, text=True)
        if result.returncode != 0:
            logging.error(f"结束通话命令执行失败: {result.stderr}")
    except Exception as e:
        logging.error(f"结束通话失败: {str(e)}")

if __name__ == "__main__":
    phone_number = "13243784433"
    make_phone_call(phone_number)
    
    # 这里可以添加你的其他操作，比如播放音频等
    
    # 如果需要结束通话，取消下面的注释
    # time.sleep(30)  # 通话持续时间
    # end_call()
